package lnkwe.util;

import com.alibaba.fastjson.JSONObject;
import com.lnkwe.common.exception.CommonException;
import com.lnkwe.config.BaseConfig;
import com.lnkwe.core.db.DbIdGenerator;
import com.lnkwe.sys.model.SysFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by lijing on 2016-07-04.
 */
public class FileUploadUtil {
    private static FileUploadUtil instance = null;
    private BaseConfig baseConfig;

    private FileUploadUtil() {
    }

    public static FileUploadUtil getInstance() {
        if (instance == null) {
            instance = new FileUploadUtil();
        }
        return instance;
    }

    public JSONObject upload(HttpServletRequest request, BaseConfig baseConfig) throws CommonException {
        JSONObject jsonObject = new JSONObject();
        this.baseConfig = baseConfig;
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> multFile = multipartRequest.getFileMap();
            Iterator<Map.Entry<String, MultipartFile>> it = multFile.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, MultipartFile> entry = it.next();
                MultipartFile file = entry.getValue();
                SysFile sysFile = this.addFile(file);
                jsonObject = sysFile.json();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(e.getMessage());
        }
        return jsonObject;

    }

    public SysFile addFile(MultipartFile file) throws CommonException {
        SysFile sysFile = new SysFile();
        try {
            InputStream in = file.getInputStream();
            String rootPath = baseConfig.getBasePath();
            String fileName = file.getOriginalFilename();
            String fileId = DbIdGenerator.generateID();
            String fileType = this.getFileType(fileName);
            String uploadFilePath = this.generatePath(fileId + fileType);
            double fileSize = file.getSize();
            String filePath = rootPath + uploadFilePath;
            System.out.println("filePath:" + filePath);
            this.createFile(filePath);
//            String url = this.formatPath(uploadFilePath);
            String url =uploadFilePath;

            FileOutputStream fileOutputStream = new FileOutputStream(filePath);

            FileIOUtil.write(in, fileOutputStream);
            sysFile.setId(fileId);
            sysFile.setFileName(fileName);
            sysFile.setFilePath(filePath);
            sysFile.setUploadFile(uploadFilePath);
            sysFile.setUrl(url);
            sysFile.setFileType(fileType);
            sysFile.setFileSize(fileSize);
        } catch (Exception e) {
            throw new CommonException(e);
        }
        return sysFile;
    }

    public String createFile(String filePath) {
        File file = new File(filePath);
        File pfile = file.getParentFile();
        if (!pfile.exists()) {
            pfile.mkdirs();
        }
        if (file.exists()) {
            file.delete();
        }
        return filePath;
    }


    private String generatePath(String id) {
        Date createTime = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(createTime);
        return "/" + cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + id;
    }

    private String getFileType(String fileName) {
        String fileType = "";
        if (StringUtil.isNotNull(fileName)) {
            fileType = fileName.substring(fileName.lastIndexOf("."));
        }
        return fileType;
    }

    public String formatPath(String filePath) {
        String url = "";
        if (StringUtil.isNotNull(filePath)) {
            url = filePath.replaceAll("\\\\", "/");
        }
        url = this.baseConfig.getStaticServer() + url;
        return url;
    }

}
